package com.demo.mvc.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.demo.fastjson.StringNotBlankFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


/** fastjson 进行json格式化
 * @author Administrator
 */
@Configuration
public class CustomizedWebMvcConfigurer implements WebMvcConfigurer {


    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
       converters.clear();
        converters.add(aliHttpMessageConverter());
    }


    @Bean
    public HttpMessageConverter aliHttpMessageConverter() {
        FastJsonHttpMessageConverter messageConverter = new FastJsonHttpMessageConverter();
        ArrayList<MediaType> list = new ArrayList<>();
        list.add(new MediaType("application", "json", StandardCharsets.UTF_8));
        messageConverter.setSupportedMediaTypes(list);
        FastJsonConfig config = new FastJsonConfig();
        config.setCharset(StandardCharsets.UTF_8);
        config.setSerializeFilters(new StringNotBlankFilter());
        config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteDateUseDateFormat);
        messageConverter.setFastJsonConfig(config);
        return messageConverter;
    }
}
